<?php
namespace Admin\Controller;

use Common\Model\SpecialStoreModel;
use Think\Model;

class PromotionController extends BaseController {
    public function group() {
        $p = max(I('param.p'), 1);
        $num = max(I('param.num'), 20);
        $this->assign('page', $p);
        $this->assign('num', $num);

        $order_field = I('param.order_field', 'id');
        $order = I('param.order', 'desc');
        $sunxu = $order == 'asc' ? 'desc' : 'asc';
        $this->assign('order_field', $order_field);
        $this->assign('order', $sunxu);
        $order = array($order_field => $order);

        $search_field = I('param.search_field');
        $search = trim(I('param.search'));
        $where[] = ' state = "1" ';
        $where[] = array('local_id' => session('userInfo')['local_id']);
        if ($search && $search_field) {
            $where[] = $search_field." like '%".$search."%'";
            $this->assign('search',$search);
            $this->assign('search_field',$search_field);
        }

        $count = M('b2c_store_promotion_group')
            ->where($where)
            ->count();
        $data = [];
        $show = '';
        if ($count) {
            $Page = new \Think\Page($count, $num);
            $show = $Page->show();
            $data = M('b2c_store_promotion_group')
                ->field('*')
                ->page($p, $num)
                ->where($where)
                ->order($order)
                ->select();
            $time = time();
            foreach ($data as &$item) {
                if ($item['start_time'] <= $time && $item['end_time'] > $time) {
                    $item['activing'] = true;
                } else {
                    $item['activing'] = false;
                }
            }
        }
        $this->assign('list',$data);
        $this->assign('page',$show);
        $this->display();
    }

    public function groupItem() {

    }

    public function groupAdd() {

        $this->display('groupEdit');
    }

    public function checkGroupPrice($total_price, array $items, array $num) {
        //计算总价格
        if (empty($total_price)) {
            $this->error('组合促销价格不能为零');
        }
        if (empty($items) || count($items) < 2) {
            $this->error('没有选择商品或者是组合商品的数量小于2');
        }
        $price_list = M('b2c_store_product')
            ->field('price')
            ->where(['store_pid'=>['in', $items], 'store_status' => 'true'])
            ->select();
        $total = 0;
        if ($price_list) {
            foreach ($price_list as $key=>$item) {
                $total = bcadd($total, bcmul($item['price'], $num[$key]));
            }
        }
        if ($total_price > $total) {
            $this->error('组合商品的价格不能大于所选商品的总价');
        }
    }

    public function groupEdit() {
        if (IS_POST) {
            $id = I('post.id');
            $name = I('post.name');
            $total_price = I('post.total_price');
            $start_time = strtotime(I('post.start_time'));
            $end_time = strtotime(I('post.end_time'));

            if ($start_time > $end_time) $this->error('开始时间不能大于结束时间');
            $this->checkGroupPrice($total_price, I('post.sp_id'), I('post.num'));
            $sp_id = I('post.sp_id');
            $num = I('post.num');
            $local_id = session('userInfo')['local_id'];
            //计算货品的总重量
            $product_ids = I('post.product_id');
            $total_weight = 0;
            if ($num && $product_ids) {
                $weight_list = M('b2c_products')
                    ->field('product_id,weight')
                    ->where(['product_id'=> array('in', join(',', $product_ids)), 'disabled' => 'false'])
                    ->select();

                if (!empty($weight_list)) {
                    foreach ($weight_list as $key => $item) {
                        $total_weight += $item['weight'] * $num[$key];
                    }
                }
            }

            $where1['end_time']=$end_time;
            $where1['start_time']=$start_time;
            $where1['local_id']=$local_id;
            $where1['type']=2;
            $e = M('store_activity_product')->where($where1)->delete();
            $activity_product=[];
            foreach($sp_id as $k){
                $activity_product[]=[
                    'local_id'=>$local_id,
                    'store_id'=>$k,
                    'start_time'=>$start_time,
                    'end_time'=>$end_time,
                    'type'=>2,

                ];
            }
            $e = M('store_activity_product')->addAll($activity_product);



            $group = array(
                'local_id' => $local_id,
                'name' => $name,
                'total_price' => $total_price,
                'total_weight' => $total_weight,
                'start_time' => $start_time,
                'end_time' => $end_time,
            );

            if (!$id) {
                $db = new Model();
                $db->startTrans();
                $insert = M('b2c_store_promotion_group')->add($group);

                if (!$insert) {
                    $db->rollback();
                    $this->error('写入失败!');
                }
                if ($sp_id && $num && count($num) == count($sp_id)) {

                    $list = M('b2c_store_product')
                        ->field('store_pid, goods_id, product_id')
                        ->where(['store_pid' => ['in', $sp_id], 'store_status' => 'true'])
                        ->order("FIELD (`store_pid`, ".implode(',', $sp_id).")")
                        ->select();

                    if ($list) {
                        foreach ($list as $k => &$item) {
                            $item['group_id'] = $insert;
                            $item['num'] = $num[$k];
                            $item['sp_id'] = $item['store_pid'];
                            unset($item['store_pid']);
                        }
                        $res = M('b2c_store_promotion_group_item')->addAll($list);
                    } else {
                        $db->rollback();
                        $this->error('失败!');
                    }
                    if($res) {
                        $db->commit();
                        redirect(U('group'));
                    } else {
                        $db->rollback();
                        $this->error('失败!');
                    }
                }
            } else {
                $db = new Model();
                $db->startTrans();
                $save = M('b2c_store_promotion_group')->where(array('id'=>$id))->save($group);
                if ($save === false) {
                    $db->rollback();
                    $this->error('写入失败!');
                }
                if ($sp_id && $num && count($num) == count($sp_id)) {
                    //删除没有勾选的
                    $delete = M('b2c_store_promotion_group_item')->where(['group_id'=>$id, 'sp_id'=>['NOT IN', $sp_id]])->delete();
                    if ($delete === false) {
                        $db->rollback();
                        $this->error('删除失败!');
                    }
                    $items = M('b2c_store_promotion_group_item')->where(['group_id'=>$id])->getField('sp_id',true);
                    $list = M('b2c_store_product')
                        ->field('store_pid, goods_id, product_id')
                        ->where(['store_pid' => ['in', $sp_id], 'store_status' => 'true'])
                        ->order("FIELD (`store_pid`, ".implode(',', $sp_id).")")
                        ->select();
                    if ($list) {
                        foreach ($list as $k => $item) {

                            if (in_array($item['store_pid'], $items)) {
                                //已有数据 更新
                                $res = M('b2c_store_promotion_group_item')->where(array('id'=>$sp_id[$k]))->save(array('num'=>$num[$k]));
                            } else {
                                //新增
                                $add = array(
                                    'group_id' => $id,
                                    'sp_id' => $item['store_pid'],
                                    'product_id' => $item['product_id'],
                                    'goods_id' => $item['goods_id'],
                                    'num' => $num[$k],
                                );
                                $res = M('b2c_store_promotion_group_item')->add($add);

                            }
                            if ($res === false) {
                                $this->rollback();
                                $this->error('失败!');
                            }
                        }
                        //exit;
                        $db->commit();
                        redirect(U('group'));

                    } else {
                        $db->rollback();
                        $this->error('失败!');
                    }
                }
            }
        } else {

            $id = I('get.id');
            if (!$id) {
                $this->error('参数缺失');
            }
            $info = $list = array();
            $info = M('b2c_store_promotion_group')->where(array('id'=>$id))->find();
            if ($info) {
                $list = M('b2c_store_promotion_group_item a')
                    ->join(C('DB_PREFIX').'b2c_store_product b on a.sp_id=b.store_pid and b.store_status="true"')
                    ->join(C('DB_PREFIX').'b2c_products c on a.product_id=c.product_id and c.disabled="false"')
                    ->field('a.*,b.price,b.store,c.name')
                    ->where(array('group_id'=>$id))
                    ->select();
                if ($list) {
                    $ids = array_column($list, 'sp_id');
                    $ids_str = join('#', $ids);
                    $this->assign('ids_str', $ids_str);
                }
                $time = time();
                if ($info['start_time'] <= $time && $info['end_time'] > $time) {
                    $info['activing'] = true;
                } else {
                    $info['activing'] = false;
                }
            }
            $this->assign('info', $info);
            $this->assign('list', $list);
            $this->display();
        }
    }


    public function getProducts() {
        $p = max(I('param.p'), 1);
        $num = max(I('param.num'), 15);
        $this->assign('page', $p);
        $this->assign('num', $num);

        $order_field = I('param.order_field', 'product_id');
        $order = I('param.order', 'desc');
        $sunxu = $order == 'asc' ? 'desc' : 'asc';
        $this->assign('order_field', $order_field);
        $this->assign('order', $sunxu);
        $order = array($order_field => $order);

        $search_field = I('param.search_field');
        $search = trim(I('param.search'));
        $local_id = session('userInfo')['local_id'];
        $where[] = array('a.local_id' =>  $local_id);
        $where[] = array('a.store_status' =>  'true');
        $where[] = array('c.disabled' =>  'false');
        $where[] = array('d.product_type_id' =>  1);
        if ($search && $search_field) {
            if ($search_field == 'bn') {
                $sfield = 'a.'.$search_field;
            } else {
                $sfield = $search_field;
            }
            $where[] = $sfield." like '%".$search."%'";
            $this->assign('search',$search);
            $this->assign('search_field',$search_field);
        }
        $count = M('b2c_store_product')
            ->alias('a')
            ->join(C('DB_PREFIX').'b2c_store_cat b on a.scate_id = b.store_cat_id', 'LEFT')
            ->join(C('DB_PREFIX').'b2c_products c on a.product_id = c.product_id')
            ->join(C('DB_PREFIX').'b2c_product_relation d on a.product_id=d.product_id')
            ->where($where)
            ->count();
        $Page = new \Think\Page($count, $num);
        $show = $Page->show();
        $fields = 'a.*,b.`cat_name`,c.`name`,c.`barcode`,c.`spec_info`';
        $list = M('b2c_store_product')
            ->alias('a')
            ->join(C('DB_PREFIX').'b2c_store_cat b on a.scate_id = b.store_cat_id', 'LEFT')
            ->join(C('DB_PREFIX').'b2c_products c on a.product_id = c.product_id')
            ->join(C('DB_PREFIX').'b2c_product_relation d on a.product_id=d.product_id')
            ->field($fields)
            ->where($where)
            ->order($order)
            ->page($p, $num)
            ->select();
        //标记出已经选中的货品
        $type_id = I('param.type_id');
        if ($type_id) {
            $where = array('group_id' => $type_id);
            $goodids = M('b2c_store_promotion_group_item')->field('sp_id')->where($where)->select();
            if ($goodids) {
                foreach ($list as &$item) {
                    if (in_array($item['store_pid'], array_column($goodids, 'sp_id'))) {
                        $item['is_show'] = true;
                    } else {
                        $item['is_show'] = false;
                    }
                }
            }
        }

        $this->assign('list',$list);
        $this->assign('page',$show);
        $this->display();
    }

    public function delItem() {
        if (!IS_AJAX) {
            $return = array(
                'status' => false,
                'message' => '非法请求',
            );
            $this->ajaxReturn($return);
        }
        $id = I('get.item_id');
        if (!$id) {
            $return = array(
                'status' => false,
                'message' => '参数缺失',
            );
            $this->ajaxReturn($return);
        }
        $db = new Model();
        $db->startTrans();
        $info = M('b2c_store_promotion_group_item')->where(['id'=>$id])->find();
        if (!$info) {
            $return = array(
                'status' => false,
                'message' => '该产品已从产品库中删除',
            );
            $this->ajaxReturn($return);
        }
        $weight = M('b2c_products')->where(['product_id'=>$info['product_id'], 'disabled' => 'false'])->getField('weight');
        $total_weight = $weight * $info['num'];
        $res = M('b2c_store_promotion_group')->where(['id'=>$info['group_id']])->setDec('total_weight', $total_weight);
        if ($res === false) {
            $db->rollback();
            $return = array(
                'status' => false,
                'message' => '更新重量错误',
            );
            $this->ajaxReturn($return);
        }
        $res = M('b2c_store_promotion_group_item')->where(array('id'=>$id))->delete();
        if ($res !== false) {
            $db->commit();
            $return = array(
                'status' => true,
                'message' => '成功',
                'data' => $res,
            );
        } else {
            $db->rollback();
            $return = array(
                'status' => false,
                'message' => '失败',
            );
        }
        $this->ajaxReturn($return);
    }

    public function delGroup() {
        if (!IS_AJAX) {
            $return = array(
                'status' => false,
                'message' => '非法请求',
            );
            $this->ajaxReturn($return);
        }
        $id = I('post.id');

        if (!$id) {
            $return = array(
                'status' => false,
                'message' => '参数缺失',
            );
            $this->ajaxReturn($return);
        }
        if (is_array($id)) {
            $id = join(',', $id);
        }

        // 删除中间表数据

        $id = I('id');
        $promotion = M('b2c_store_promotion_group');
        $where['id'] = $id;
        $where['local_id'] = session('userInfo')['local_id'];
        $discount_coupon_msg = $promotion->where($where)->find();
        $where1['end_time']=$discount_coupon_msg['end_time'];
        $where1['start_time']=$discount_coupon_msg['start_time'];
        $where1['local_id']=session('userInfo')['local_id'];
        $where1['type']=2;
        M('store_activity_product')->where($where1)->delete();

        //

        $res = M('b2c_store_promotion_group')->where(array('id'=>array('in', $id)))->save(['state'=>'0']);

        if ($res !== false) {
            $return = array(
                'status' => true,
                'message' => '成功',
                'data' => $res,
            );
        } else {
            $return = array(
                'status' => false,
                'message' => '失败',
            );
        }
        $this->ajaxReturn($return);
    }


    /**
     * 添加产品
     */
    public function productAdd()
    {

        $name = I('name', '', htmlspecialchars());
        $id = I('id', '', htmlspecialchars());

        if (!empty($name)) {
            $where['b.name'] = array('like', "%$name%");
        }

        $page = max(I('get.p'), 1);
        $num = max(I('get.num'), 20);

        $order = "a.store_pid desc";
        $product_relation_model = M('b2c_store_product a');

        $where['a.local_id'] = $this->local_id;
        $where['a.store_status'] = 'true';
        $where['b.disabled'] = 'false';

        $field = "a.marketprice,a.price,a.store,a.discount,a.store_pid,b.product_id,b.goods_id,b.title,b.name,b.spec_info,a.local_id";

        // 可售货品
        $count = $product_relation_model->join(C('DB_PREFIX') . 'b2c_products b on a.product_id=b.product_id')
            ->where($where)
            ->count();

        $Page = new \Think\Page($count, $num);
        $show = $Page->show();
        $product_relation_msg = $product_relation_model->join(C('DB_PREFIX') . 'b2c_products b on a.product_id=b.product_id', 'left')
            ->where($where)
            ->order($order)
            ->field($field)
            ->page($page, $num)
            ->select();

//        $menu = M('store_carousel')->where(['id' => $id])->find();
//        $value = unserialize($menu['value']);

        $this->assign([
            'product_relation_msg' => $product_relation_msg,
            'show' => $show,
            'id' => $id,
//            'value' => $value
        ]);

        $this->display();
    }



}